package com.huiyun.project.pay.biz.mq;

import com.alibaba.fastjson.JSON;
import com.huiyun.project.pay.client.vo.NotifyResp;
import com.huiyun.project.pay.client.consts.PayConst;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author 01
 * @date 2019-08-08
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class NotifyProducer {
    private final RocketMQTemplate rocketMQTemplate;

    /**
     * 发送mq事务消息
     *
     * @return
     */
    @Async
    public void sendMessage(NotifyResp notifyResp) {
        log.info("MQ发送支付通知消息开始:{}", JSON.toJSONString(notifyResp));
        // 发送半消息
        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(
                PayConst.TX_PRODUCER_GROUP_NOTICE, notifyResp.getDestination(),
                // 消息体
                MessageBuilder.withPayload(notifyResp)
                        .setHeader("uniqueKey", notifyResp.getMchId() + ":" + notifyResp.getMchOrderNo())
                        .build(),
                // 传递到executeLocalTransaction的参数
                notifyResp);
        log.info("MQ发送支付通知消息结果:{}", JSON.toJSONString(result));
        Assert.isTrue(result.getSendStatus().compareTo(SendStatus.SEND_OK) == 0, "mq send error");
    }


    /**
     * 发送退款mq事务消息
     *
     * @return
     */
    @Async
    public void sendRefundMessage(NotifyResp notifyResp) {
        log.info("MQ发送支付通知消息开始:{}", JSON.toJSONString(notifyResp));
        // 发送半消息
        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(
                PayConst.TX_PRODUCER_GROUP_REFUND, notifyResp.getDestination(),
                // 消息体
                MessageBuilder.withPayload(notifyResp)
                        .setHeader("uniqueKey", notifyResp.getMchId() + ":" + notifyResp.getMchOrderNo())
                        .build(),
                // 传递到executeLocalTransaction的参数
                notifyResp);
        log.info("MQ发送支付通知消息结果:{}", JSON.toJSONString(result));
        Assert.isTrue(result.getSendStatus().compareTo(SendStatus.SEND_OK) == 0, "mq send error");
    }
}